import { NextApiRequest, NextApiResponse } from 'next'
import {withIronSessionApiRoute} from 'iron-session/next'
import {prepareConnection} from 'db/index'
import { User } from 'db/entity/index'
import {ironOptions} from 'config/index'
import { ISession} from 'pages/api/index'
import { EXCEPTION_USER } from 'pages/api/config/codes'

export default withIronSessionApiRoute(update,ironOptions)

async function update(req: NextApiRequest, res: NextApiResponse) {
    const sesssion: ISession = req.session
    const {userId} = sesssion
    const {nickname='',job='',introduce=''} = req?.body
    // 连接数据库
    const db = await prepareConnection()
    const UserRepo = db.getRepository(User)
    const user = await UserRepo.findOne({where: {id: Number(userId)}})
    if (user) {
        user.nickname = nickname
        user.job = job
        user.introduce = introduce
        const resUser = await UserRepo.save(user)
        res.status(200).json({code: 0, msg: '', data: resUser})
    } else {
        res?.status(200).json({...EXCEPTION_USER.NOT_FOUND})
    }
}